import { userStore } from '@/biz/user'
import server from '@/config/server/index.js'

let api = {
  login: () => {
    return server.api().post('/api/v1/auth/login').auth(false).config(false)
  },
  info: () => {
    return server.api().get('/api/v1/user/getUserInfo')
  }
}

function login(info) {
  uni.showLoading()
  return api
    .login()
    .fetch(info)
    .then((res) => {
      server.auth.setInfo({
        authorization: res.tokenValue,
        userId: res.userId
      })
      return api
        .info()
        .fetch()
        .then((res) => {
          uni.hideLoading()
          res.login = info.phone
          userStore().login(res)
          return res
        })
        .catch(() => {
          uni.hideLoading()
        })
    })
    .catch((err) => {
      uni.showToast({ icon: 'none', title: err.message })
      throw err
    })
}

function loginByAuth(phone) {
  return login({ phone, port: 1, type: 2 })
}

export default {
  loginByAuth
}
